import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time

# SMTP服务器地址
EMAIL_ADDRESS = "csuxhf@163.com"  # 邮箱的地址
EMAIL_PASSWORD = "HWKSHHGZVWTMCUEB"  # 授权码
mail_host = "smtp.163.com"  #163邮箱服务器地址

send_to = ["121068023@qq.com"] # 定义好收件人，可以有多个
subject = "xxxx项目回归测试"
str_time = time.strftime("%Y-%m-%d") #获取测试时间

class SendEmail:
    def send_email(self,m,file):
        '''
        :param m:  测试用例的数量
        :param file: 附件的名字
        :return:
        '''
        #使用MIMEMultipart构建邮件内容
        msg = MIMEMultipart('mixed')

        '''
        multipart类型主要有三种子类型：mixed、alternative、related
        '''
        msg["Subject"] = subject

        # html格式的邮件正文
        content = '''
        <html>
        <body>
        <p><strong>回归测试用例</strong></p>
        <p>测试内容如下：</p>
        <table width="500" bordercolor="black" border="1" cellspacing="0">
         <tr>
          <td><strong>测试人员</strong></td>
          <td><strong>用例数量</strong></td>
          <td><strong>测试时间</strong></td>
         </tr>
         <tr>
          <td>张三</td>
          <td>{}</td>
          <td>{}</td>
         </tr>
        </table>
        </body>
        </html>
        '''.format(m,str_time)
        msg.attach(MIMEText(content, 'html', 'utf-8')) #content正文内容、html正文数据格式

        # 构造附件
        # 读取附件
        f = open(file, 'rb')
        res = f.read() #以字节流的形式读取文件内容
        f.close()
        # 添加附件
        att1 = MIMEText(res, 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        #设置发送邮件时的附件的数据格式，application/octet-stream：表示字节流

        # 设置附件文件的名字
        filename = file.split("\\")[-1]
        att1["Content-Disposition"] = 'attachment; filename="{}"'.format(filename)
        msg.attach(att1)

        ## 发送邮件
        s = smtplib.SMTP()  # 实例化对象
        s.connect(mail_host, 25)  # 连接163邮箱服务器，端口号为25
        s.login(EMAIL_ADDRESS, EMAIL_PASSWORD)  # 登录邮箱
        s.sendmail(EMAIL_ADDRESS,send_to, msg.as_string())
        s.quit()

sendmail = SendEmail()

if __name__ == '__main__':
    sd = SendEmail()
    sd.send_email(20,r'E:\课程\Web自动化测试\code\MyProject\common\dss.html')
